<?php
/**
 * Created by PhpStorm.
 * User: zhangrxiang
 * Date: 2016/9/28
 * Time: 9:40
 */


$i = 0;
exportCSV([
    'id',
    'c1',
    'c2',
    'c3',
    'c4'
],[
    ['id' => $i,
    'c1' => 'c1--'.$i,
    'c2' => 'c2--'.$i,
    'c3' => 'c3--'.$i,
    'c4' => (string)time()]
]);
# We will use this function to generate a CSV
function exportCSV($headings=[], $rows=[], $filename=false)
{
    # Ensure that we have data to be able to export the CSV
    if ((!empty($headings)) AND (!empty($rows)))
    {
        # modify the name somewhat
        $name = ($filename !== false) ? $filename . ".csv" : "export.csv";

        # Set the headers we need for this to work
        header('Content-Type: text/csv; CHARSET=utf-8');
        header('Content-Disposition: attachment; filename=' . $name);

        # Start the ouput
        $output = fopen('php://output', 'w');

        # Create the headers
        fputcsv($output, $headings);

        # Then loop through the rows
        foreach($rows as $row)
        {
            # Add the rows to the body
            fputcsv($output, $row);
        }

        # Exit to close the stream off
        exit();
    }

    # Default to a failure
    return false;
}
